package com.aids_malaria.ui.report;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.MemberDataAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.helper.PointLengthFilter;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.MemberData;
import com.aids_malaria.http.response.MemberDataResponse;
import com.aids_malaria.ui.datacollect.CountySelectActivity;
import com.aids_malaria.ui.datacollect.DataQueryActivity;
import com.aids_malaria.ui.datacollect.VillageSelectActivity;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DateUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.ToastUtil;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MemberDataActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_medical_treatment)
    TextView tv_medical_treatment;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.tv_all_member)
    TextView tv_all_member;
    @BindView(R.id.tv_uncertain_sick)
    TextView tv_uncertain_sick;
    @BindView(R.id.tv_certain_sick)
    TextView tv_certain_sick;
    @BindView(R.id.tv_sick_percent)
    TextView tv_sick_percent;
    @BindView(R.id.tv_sex_percent)
    TextView tv_sex_percent;
    @BindView(R.id.et_county)
    TextView et_county;
    @BindView(R.id.et_village)
    TextView et_village;
    @BindView(R.id.et_start_time)
    TextView et_start_time;
    @BindView(R.id.et_end_time)
    TextView et_end_time;
    @BindView(R.id.et_age1)
    EditText et_age1;
    @BindView(R.id.et_age2)
    EditText et_age2;
    @BindView(R.id.et_x1)
    EditText et_x1;
    @BindView(R.id.et_x2)
    EditText et_x2;
    @BindView(R.id.et_y1)
    EditText et_y1;
    @BindView(R.id.et_y2)
    EditText et_y2;

    private MemberDataAdapter memberDataAdapter;
    private List<MemberData> mData = new ArrayList<>();

    private String county_code = "",county_name = "";
    private String village_code = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_member_data;
    }

    @Override
    protected void initView() {
        super.initView();
        tv_title.setText(getString(R.string.member_title));
        tv_medical_treatment.setVisibility(View.VISIBLE);

        PointLengthFilter pointLengthFilter = new PointLengthFilter(6);
        et_x1.setFilters(new InputFilter[]{pointLengthFilter});
        et_x2.setFilters(new InputFilter[]{pointLengthFilter});
        et_y1.setFilters(new InputFilter[]{pointLengthFilter});
        et_y2.setFilters(new InputFilter[]{pointLengthFilter});

        et_x1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_x2.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_y1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_y2.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        initRefreshLayout();
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();

//        getPersonData(); // 获取数据
    }

    @OnClick({R.id.ll_back, R.id.iv_search, R.id.tv_medical_treatment, R.id.iv_select, R.id.iv_start_time_select, R.id.iv_end_time_select,
    R.id.iv_county_select,R.id.et_county,R.id.et_village,R.id.et_start_time,R.id.et_end_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_search:

                getPersonData();
                // 搜索
                break;
            case R.id.tv_medical_treatment:
                // 跳转药物治疗
                startActivity(MedicalTreatmentActivity.class);
                break;
            case R.id.iv_select:
            case R.id.et_village:
                // 选择村
                Bundle bundle = new Bundle();
                bundle.putInt(Events.TYPE_KEY,Events.TYPE_MEMBER_DATA);
                bundle.putString("county_code",county_code);
                bundle.putString("county_name",county_name);
                startActivity(VillageSelectActivity.class,bundle);
                break;
            case R.id.iv_start_time_select:
            case R.id.et_start_time:
                // 发病时间段 开始时间
                DateUtil.newTimeSelect(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        et_start_time.setText(DateUtil.getFullTimeFormatter().format(date));
                    }
                }).show();
                break;
            case R.id.iv_end_time_select:
            case R.id.et_end_time:
                // 发病时间段 结束时间
                DateUtil.newTimeSelect(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        et_end_time.setText(DateUtil.getFullTimeFormatter().format(date));
                    }
                }).show();
                break;
            case R.id.iv_county_select:
            case R.id.et_county:
                Bundle b = new Bundle();
                b.putInt(Events.TYPE_KEY,Events.TYPE_MEMBER_DATA);
                startActivity(CountySelectActivity.class,b);
                break;
        }
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getPersonData();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        memberDataAdapter = new MemberDataAdapter(mContext, R.layout.item_member_data, mData);
        rv_data.setAdapter(memberDataAdapter);
        memberDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(MemberDataActivity.this, DataQueryActivity.class);
                intent.putExtra(DataQueryActivity.AREA_CODE, mData.get(position).getArea_code());
                intent.putExtra("MemberData", GsonUtil.beanToJson(mData.get(position)));
                startActivity(intent);
            }
        });
    }

    /**
     * 村选择回调
     * @param villageSelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.VillageSelectEvent villageSelectEvent) {
        if (villageSelectEvent.getType() == Events.TYPE_MEMBER_DATA){
            village_code = villageSelectEvent.getAreaV().getVillage_code();
            et_village.setText(villageSelectEvent.getAreaV().getVillage_name());
        }
    }

    /**
     * 县选择回调
     *
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent) {
        if (countySelectEvent.getType() == Events.TYPE_MEMBER_DATA){
            AreaC areaC = countySelectEvent.getAreaC();
            county_code = areaC.getCounty_code();
            county_name = areaC.getCounty_name();
            et_county.setText(county_name);

            //清空之前的选择

            village_code = "";
            et_village.setText("");
        }
    }

    public void getPersonData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("area_code", "");
        if (!TextUtils.isEmpty(county_code)){
            map.put("area_code", county_code);
        }
        if (!TextUtils.isEmpty(village_code)){
            map.put("area_code", village_code);
        }
        map.put("age_fr", et_age1.getText().toString().trim());
        map.put("age_to", et_age2.getText().toString().trim());
        map.put("x_fr", et_x1.getText().toString().trim());
        map.put("x_to", et_x2.getText().toString().trim());
        map.put("y_fr", et_y1.getText().toString().trim());
        map.put("y_to", et_y2.getText().toString().trim());
        map.put("onset_time_fr", et_start_time.getText().toString().trim());
        map.put("onset_time_to", et_end_time.getText().toString().trim());
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPersonData(map)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<MemberDataResponse>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(MemberDataResponse data) throws Exception {
                        if (data != null) {
                            List<MemberData> sub_data = data.getSub_data();
                            if (sub_data != null) {
                                mData.clear();
                                mData.addAll(sub_data);
                                memberDataAdapter.notifyDataSetChanged();
                            }
                            // 设置数据
                            tv_all_member.setText(data.getPerson_sum());
                            tv_certain_sick.setText(data.getConfirmed_cases_num());
                            tv_uncertain_sick.setText(data.getSuspected_cases_num());
                            tv_sex_percent.setText(data.getSex_ratio());
                            tv_sick_percent.setText(data.getInfection_rate());
                        }
                    }

                    @Override
                    protected void onFinish() {
                        refresh_layout.finishRefresh();
                        getLoadingDialog().dismiss();
                    }
                });
    }

}
